package com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.HddcGeomorphysvyregionRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.entity.HddcGeomorphysvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.repository.HddcWyGeomorphysvyregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.repository.HddcWyGeomorphysvyregionRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.repository.entity.HddcWyGeomorphysvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.service.HddcWyGeomorphysvyregionService;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.viewobjects.HddcWyGeomorphysvyregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyRegion.viewobjects.HddcWyGeomorphysvyregionVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lihelei
 * @date 2020-12-01
 */
@Service
public class HddcWyGeomorphysvyregionServiceImpl implements HddcWyGeomorphysvyregionService {

	@Autowired
    private HddcWyGeomorphysvyregionRepository hddcWyGeomorphysvyregionRepository;
    @Autowired
    private HddcWyGeomorphysvyregionNativeRepository hddcWyGeomorphysvyregionNativeRepository;
    @Autowired
    private HddcGeomorphysvyregionRepository hddcGeomorphysvyregionRepository;


    @Override
    public JSONObject queryHddcWyGeomorphysvyregions(HddcWyGeomorphysvyregionQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeomorphysvyregionEntity> hddcWyGeomorphysvyregionPage = this.hddcWyGeomorphysvyregionNativeRepository.queryHddcWyGeomorphysvyregions(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeomorphysvyregionPage);
        return jsonObject;
    }


    @Override
    public HddcWyGeomorphysvyregionEntity getHddcWyGeomorphysvyregion(String uuid) {
        HddcWyGeomorphysvyregionEntity hddcWyGeomorphysvyregion = this.hddcWyGeomorphysvyregionRepository.findById(uuid).orElse(null);
         return hddcWyGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvyregionEntity saveHddcWyGeomorphysvyregion(HddcWyGeomorphysvyregionEntity hddcWyGeomorphysvyregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeomorphysvyregion.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyGeomorphysvyregion.getCreateUser())){
            hddcWyGeomorphysvyregion.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeomorphysvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeomorphysvyregion.setIsValid("1");

        HddcGeomorphysvyregionEntity hddcGeomorphysvyregionEntity=new HddcGeomorphysvyregionEntity();
        BeanUtils.copyProperties(hddcWyGeomorphysvyregion,hddcGeomorphysvyregionEntity);
        hddcGeomorphysvyregionEntity.setExtends4(hddcWyGeomorphysvyregion.getTown());
        hddcGeomorphysvyregionEntity.setExtends5(String.valueOf(hddcWyGeomorphysvyregion.getLon()));
        hddcGeomorphysvyregionEntity.setExtends6(String.valueOf(hddcWyGeomorphysvyregion.getLat()));
        this.hddcGeomorphysvyregionRepository.save(hddcGeomorphysvyregionEntity);

        this.hddcWyGeomorphysvyregionRepository.save(hddcWyGeomorphysvyregion);
        return hddcWyGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvyregionEntity updateHddcWyGeomorphysvyregion(HddcWyGeomorphysvyregionEntity hddcWyGeomorphysvyregion) {
        HddcWyGeomorphysvyregionEntity entity = hddcWyGeomorphysvyregionRepository.findById(hddcWyGeomorphysvyregion.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeomorphysvyregion);
        hddcWyGeomorphysvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeomorphysvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeomorphysvyregionRepository.save(hddcWyGeomorphysvyregion);
        return hddcWyGeomorphysvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeomorphysvyregions(List<String> ids) {
        List<HddcWyGeomorphysvyregionEntity> hddcWyGeomorphysvyregionList = this.hddcWyGeomorphysvyregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyGeomorphysvyregionList) && hddcWyGeomorphysvyregionList.size() > 0) {
            for(HddcWyGeomorphysvyregionEntity hddcWyGeomorphysvyregion : hddcWyGeomorphysvyregionList) {
                this.hddcWyGeomorphysvyregionRepository.delete(hddcWyGeomorphysvyregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeomorphysvyregion(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeomorphysvyregionNativeRepository.queryHddcWyGeomorphysvyregion(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeomorphysvyregionEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeomorphysvyregionEntity> list = hddcWyGeomorphysvyregionRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeomorphysvyregionEntity> hddcWyGeomorphysvyregionEntity = hddcWyGeomorphysvyregionNativeRepository.exportRegion(queryParams);
        List<HddcWyGeomorphysvyregionVO> list=new ArrayList<>();
        for (HddcWyGeomorphysvyregionEntity entity:hddcWyGeomorphysvyregionEntity) {
            HddcWyGeomorphysvyregionVO hddcWyGeomorphysvyregionVO=new HddcWyGeomorphysvyregionVO();
            BeanUtils.copyProperties(entity,hddcWyGeomorphysvyregionVO);
            list.add(hddcWyGeomorphysvyregionVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"微地貌测量面-面","微地貌测量面-面", HddcWyGeomorphysvyregionVO.class,"微地貌测量面-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeomorphysvyregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeomorphysvyregionVO.class, params);
            List<HddcWyGeomorphysvyregionVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyGeomorphysvyregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyGeomorphysvyregionVO hddcWyGeomorphysvyregionVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyGeomorphysvyregionVO.getRowNum() + "行" + hddcWyGeomorphysvyregionVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyGeomorphysvyregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyGeomorphysvyregionEntity hddcWyGeomorphysvyregionEntity = new HddcWyGeomorphysvyregionEntity();
            HddcWyGeomorphysvyregionVO hddcWyGeomorphysvyregionVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyGeomorphysvyregionVO, hddcWyGeomorphysvyregionEntity);
            saveHddcWyGeomorphysvyregion(hddcWyGeomorphysvyregionEntity);
        }
    }

    @Override
    public List<HddcWyGeomorphysvyregionEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyGeomorphysvyregionEntity> list = hddcWyGeomorphysvyregionRepository.findAllByCreateUserAndIsValid(userId,isValid);
        return list;
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeomorphysvyregionEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvyregionRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeomorphysvyregionEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvyregionRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeomorphysvyregionEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvyregionRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeomorphysvyregionEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvyregionRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }








}
